package com.aa;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.aa.autoanswer.AutoAnswerIntentService;
import com.aa.http.HttpOperation;


import android.R.bool;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.renderscript.Element;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CallWaitActivity extends Activity {

	private String TAG = "CallWaitActivity";
	private TextView mtvCallSataus;
	private ImageView mivUserImage;
	private TextView mtvUserName;
	private TextView mtvUserNumber;
	private TextView mtvCallTime;
	private Button mbtnHFP;
	private Button mbtnSilence;
	private Button mbtnEndCall;
	private boolean misSilence = true;
	private boolean misHFP = true;
	private AudioManager mAudioManager;
	private int mHour = 0;
	private int mMinute = 0;
	private int mSecond = 0;
	private int mCount = 0;
	private String mErrorStr;
	//private String mUrl = "http://192.168.89.42/AAproject/api/mobile.php";
	private String mUrl = "http://121.9.64.196:8087/AAproject/api/mobile.php";
	private boolean isCallSucceed = false;
	private Handler mHandler;
	private String mReturnErrMSG = "";
	private Timer mTimer = new Timer();
	private TimerTask mTimerTask = new TimerTask(){
		
		@Override
		public void run() {
			mCount++;
			if (mCount > 59) {
				mCount = 0;
				mMinute++;
				if (mMinute > 60) {
					mMinute = 0;
					mHour++;
				}
			}
			
			if (Common.iIsEndCallUI) {
				mHandler.sendEmptyMessage(4);
				Common.iIsEndCallUI = false;
			}
			
			Message _Message = new Message();
			mHandler.sendEmptyMessage(2);
			
		}
	};
	@Override
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.callwait);
		mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
		initView();
		initListener();
		Intent _Intent = new Intent();
		_Intent.setClass(CallWaitActivity.this, AutoAnswerIntentService.class);
		startService(_Intent);
		Log.i(TAG, "CallWaitActivity onCreate ");
		
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					mtvCallSataus.setText(R.string.cw_call_success);
					mTimer.schedule(mTimerTask, 1000, 1000);
					isCallSucceed = true;
				
					break;
				case 1:
					Toast.makeText(CallWaitActivity.this, R.string.call_wait_fail, 3000).show();
					break;
				case 2:																				
					mtvCallTime.setText(mHour + ":" + mMinute + ":" + mCount);
					break;
				case 3:
					Toast.makeText(CallWaitActivity.this, mErrorStr, 3000).show();
					break;
				case 4: 
					finish();
					break;
				}
			}
			
		};
		
		if (Common.iServceCall == true) {
			callServce();
			Common.iServceCall = false;
		}else {
			callBack();
		}
		
		
	}
	private void stopTimer(){
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}
	private void initView(){
		mtvCallSataus = (TextView)findViewById(R.id.cw_status_tip);
		mivUserImage = (ImageView)findViewById(R.id.cw_iv_userimage);
		mtvUserName = (TextView)findViewById(R.id.cw_tv_name);
		mtvUserNumber = (TextView)findViewById(R.id.cw_tv_number);
		mtvUserNumber.setText(Common.iCallNumber.trim());
		mtvCallTime = (TextView)findViewById(R.id.cw_callTimer);
		mbtnHFP = (Button)findViewById(R.id.cw_btn_mt);
		mbtnSilence = (Button)findViewById(R.id.cw_btn_voice);
		mbtnEndCall = (Button)findViewById(R.id.cw_btn_end);	
	}
	
	private void initListener(){
		mbtnHFP.setOnClickListener(new OnCallSatausClickListener());
		mbtnSilence.setOnClickListener(new OnCallSatausClickListener());
		mbtnEndCall.setOnClickListener(new OnCallSatausClickListener());
	}
	
	private class OnCallSatausClickListener implements OnClickListener{
	
		@Override
		public void onClick(View v) {
			int _ID = v.getId();
			switch (_ID) {
			case R.id.cw_btn_end:
				if (isCallSucceed) {
					stopTimer();
					isCallSucceed = false;
				}
			
				
				finish();
				break;
			case R.id.cw_btn_voice:
				if (!mAudioManager.isMicrophoneMute()) {
					mbtnSilence.setBackgroundResource(R.drawable.voice_select);
				}else {
					mbtnSilence.setBackgroundResource(R.drawable.voice_none);
				}
				mAudioManager.setMicrophoneMute(!mAudioManager.isMicrophoneMute());
				break;
			case R.id.cw_btn_mt:
				mAudioManager.setSpeakerphoneOn(!mAudioManager.isSpeakerphoneOn());
				if (mAudioManager.isSpeakerphoneOn()) {
					mbtnHFP.setBackgroundResource(R.drawable.mt_select);
				}else {
					mbtnHFP.setBackgroundResource(R.drawable.mt_none);
				}
				break;		
				
			default:
				break;
			}
			
		}
	}
		private void callBack(){
			
			final JSONObject _SendJson = new JSONObject();
			JSONObject _BodyJson = new JSONObject();
			JSONObject _HeadJson = new JSONObject();
			try {
				_HeadJson.put("v", Common.iVersion);
				_HeadJson.put("time", System.currentTimeMillis());
				_HeadJson.put("cmd", 6);
				_HeadJson.put("mac", Common.iMac);
				
				_BodyJson.put("uid", Common.iUID);
				
				_BodyJson.put("pnumber", Common.iMyPhoneNumber);
				_BodyJson.put("inumber", Common.iCallNumber.trim());
				
				_SendJson.put("head", _HeadJson);
				_SendJson.put("body", _BodyJson);
				Log.i(TAG, "send = " + _SendJson.toString());
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			new Thread(new Runnable() {				
				@Override
				public void run() {
				
					String _Result = HttpOperation.postRequestJSONFormat(mUrl, _SendJson.toString());
					if (_Result == null) {
						mHandler.sendEmptyMessage(1);
						return;
					}
					Log.i(TAG, "_Result = " + _Result);	
					try {
						  JSONObject _JsonObject = new JSONObject(_Result);
							  
							
						  JSONObject _Head = _JsonObject.getJSONObject("head");  
						  JSONObject _Body = _JsonObject.getJSONObject("body");
						  if (_Body.getInt("rcode") == 1) {
							
							  Common.iShowAutoAnswer = true;
							  mHandler.sendEmptyMessage(0);
							 
						}else {
							mErrorStr = _Body.getString("msg");
							mHandler.sendEmptyMessage(3);
						}
						
					} catch (JSONException e) {
						 
						e.printStackTrace();
					}					
				}
			}).start();		
	}

	private void callServce(){
		final JSONObject _SendJson = new JSONObject();
		JSONObject _BodyJson = new JSONObject();
		JSONObject _HeadJson = new JSONObject();
		try {
			_HeadJson.put("v", Common.iVersion);
			_HeadJson.put("time", System.currentTimeMillis());
			_HeadJson.put("cmd", 16);
			_HeadJson.put("mac", Common.iMac);
			
			_BodyJson.put("uid", Common.iUID);
			
			_BodyJson.put("pnumber", Common.iMyPhoneNumber);
			
			
			_SendJson.put("head", _HeadJson);
			_SendJson.put("body", _BodyJson);
			Log.i(TAG, "send = " + _SendJson.toString());
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		new Thread(new Runnable() {				
			@Override
			public void run() {
			
				String _Result = HttpOperation.postRequestJSONFormat(mUrl, _SendJson.toString());
				if (_Result == null) {
					mHandler.sendEmptyMessage(1);
					return;
				}
				Log.i(TAG, "_Result = " + _Result);	
				try {
					  JSONObject _JsonObject = new JSONObject(_Result);
						  
						
					  JSONObject _Head = _JsonObject.getJSONObject("head");  
					  JSONObject _Body = _JsonObject.getJSONObject("body");
					  if (_Body.getInt("rcode") == 1) {
						
						  Common.iShowAutoAnswer = true;
						  mHandler.sendEmptyMessage(0);
						 
					}
					
				} catch (JSONException e) {
					 
					e.printStackTrace();
				}					
			}
		}).start();		
	}	
		
	@Override
	protected void onDestroy() {
			
			super.onDestroy();
			if (isCallSucceed) {
				stopTimer();
				isCallSucceed = false;
			}
			 Common.iShowAutoAnswer = false;
		}
	
	

}
